package cn.edu.imnu.Controller;
import cn.edu.imnu.entity.ResponseData;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import cn.edu.imnu.entity.vo.UploadResultVo;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * 通用控制器
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    @Resource
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @Value("${minio.endpoint}")
    private String endpoint;

    @PostMapping("/uploadminio")
    public ResponseData<UploadResultVo> uploadFile(@RequestParam("file") MultipartFile file) {
        UploadResultVo uploadResultVo = new UploadResultVo();
        if (file.isEmpty()) {
            return ResponseData.warn("Error: File is empty");
        }
        try {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString() + fileExtension;
            // 上传文件到MinIO
            try (InputStream inputStream = file.getInputStream()) {
                minioClient.putObject(
                        PutObjectArgs.builder()
                                .bucket(bucketName)
                                .object(uniqueFileName)
                                .stream(inputStream, file.getSize(), -1)
                                .contentType(file.getContentType())
                                .build()
                );
            }

            // 构建文件访问URL
            String fileUrl = String.format("%s/%s/%s", endpoint, bucketName, uniqueFileName);
            uploadResultVo.setUrl(fileUrl);
            uploadResultVo.setBucket(bucketName);
            uploadResultVo.setFileName(originalFilename);
        } catch (MinioException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
            ResponseData.warn("Error uploading file: " + e.getMessage());
        }
        return ResponseData.ok(uploadResultVo);
    }


}
